<template>
  <!-- 品牌 车型 车系 配置界面 -->
  <div id="ra_carId">
    <magic-header v-if="$route.params.is == 'select'" titleName="车辆选择" :returnNative="$route.params.native"></magic-header>
    <!--  try 1-试驾 不传 -->
    <span v-if="($route.params.is == 'repair' || $route.params.is == 'protect') && (user && user.userId ? true : false) && signedCars.length > 0">
      <!-- smaller header 注册车辆(保养 维修) -->
      <div class="smaller-header">注册车辆</div>
      <!-- 我的车辆(保养 维修) -->
      <cells>
        <cell label="我的车辆" v-tap="{methods: toSignedCar}"></cell>
      </cells>
    </span>

    <!-- smaller header 全部品牌 -->
    <div class="smaller-header">全部品牌</div>
    <!-- car select -->
    <cells>
      <cell label="品牌" v-tap="{methods: toBrands}" :value="brand.name"></cell>
      <cell label="车系" v-tap="{methods: toSeries}" :value="serie.name"></cell>
      <cell label="车型" v-tap="{methods: toTypes}" :value="type.name"></cell>
    </cells>
    <!-- 品牌选择 -->
    <!-- <icar-dialog :isShow="brandListShow" @dialogClose="brandListClose"> -->
    <grid-list v-if="brandListShow">
      <div slot="title" class="grid-title">请选择</div>
      <div>
        <div v-for="(item, index) in brandList" :key="index">
          <div class="item brand" v-tap="{methods: getBrand, item: item}">
            <img :src="addPath(item.logo)" alt="">
            <span v-html="item.name"></span>
          </div>
        </div>
      </div>
      <div slot="foot" class="grid-cancel">
        <button v-tap="{methods:brandListClose}">取消</button>
      </div>
    </grid-list>
    <!-- </icar-dialog> -->
    <!-- 车系 -->
    <grid-list v-if="serieListShow">
      <div slot="title" class="grid-title">请选择</div>
      <div>
        <div v-for="(item, index) in brand.series" :key="index">
          <div class="item serie" v-tap="{methods: getSerie, item: item}">
            <img :src="addPath(item.image)" alt="">
            <span v-html="item.name"></span>
          </div>
        </div>
      </div>
      <div slot="foot" class="grid-cancel">
        <button v-tap="{methods:serieListClose}">取消</button>
      </div>
    </grid-list>
    <!-- 类型 -->
    <grid-list v-if="typeListShow">
      <div slot="title" class="grid-title">请选择</div>
      <div>
        <div v-for="(item, index) in serie.products" :key="index">
          <div class="item product" v-tap="{methods: getType, item: item}">
            <span v-html="item.name"></span>
          </div>
        </div>
      </div>
      <div slot="foot" class="grid-cancel">
        <button v-tap="{methods:typeListClose}">取消</button>
      </div>
    </grid-list>

    <!-- 我的车辆 -->
    <grid-list v-if="signedCarsShow">
      <div v-for="(item, index) in signedCars" :key="index">
        <div class="item brand" v-tap="{methods: getSignedCar, item: item}">
          <img :src="item.brandLogo" v-if="item.brandLogo">
          <img :src="defaultCarImg" v-else>
          <span>{{ item.plateNumber }}</span>
        </div>
      </div>
    </grid-list>
  </div>

</template>

<script>
// components
import cells from "components/cells";
import cell from "components/cell";
import gridList from "components/gridList/gridList";
import icarDialog from "components/dialog/dialog";
import magicHeader from "components/magicHeader";
//images
import defaultCarImg from "assets/default_car_icon.png";
// services
import ListBrand from "services/appointment/ListBrand";
import QueryCarInfoList from "services/appointment/QueryCarInfoList";
// Store
import carStore from "services/seeGoods/car-compare";

export default {
  components: { cells, cell, gridList, icarDialog, magicHeader },
  data() {
    return {
      defaultCarImg,
      brandList: [],
      brand: {}, // 品牌
      _brand: {}, // 品牌 cache
      brandListShow: false,
      serie: {}, // 车系
      _serie: {}, // 车系
      serieListShow: false,
      type: {}, // 车型
      _type: {}, // 车型
      typeListShow: false,
      // 绑定的车辆信息
      signedCars: [],
      signedCarsShow: false,
      showCar: null,
      firstVisit: true,
      fromRoute: '' // 从何处进入
    };
  },
  created() {
  },
  methods: {
    // 跳转汽车品牌
    toBrands() {
      // debug
      // alert(
      //   `ListBrand: req=>
      // userId:${this.user.userId}
      // shopId:${this.user.shop.id}
      // `
      // );

      if (this.brandList.length == 0) {
        ListBrand.bind(this)(
          {
            userId: this.user.userId,
            shopId: this.user.shop.id
            // productId: this.user.producted,
          },
          resp => {
            this.brandList = resp.brands;
            // debug
            // alert(
            //   `ListBrand: resp=>
            //   brandList:${this.brandList}`
            // );
          }
        );
      }
      this.brandListShow = true;
    },
    // 获取汽车品牌
    getBrand(params) {
      this._brand = this.brand;
      this.brand = params.item;
      this.brandListShow = false;
      // 两次选择品牌不同, 则需要重新选择车系和车型
      if (this._brand.id != this.brand.id) {
        this.serie = {};
        this.type = {};
      }
    },
    // 跳转汽车车系
    toSeries() {
      if ("id" in this.brand) {
        this.serieListShow = true;
      } else {
        this.$.toast("请先选择品牌");
      }
    },
    // 获取汽车车系
    getSerie(params) {
      this._serie = this.serie;
      this.serie = params.item;
      this.serieListShow = false;
      // 两次选择车系不同, 则需要重新选择车型
      if (this._serie.id != this.serie.id) {
        this.type = {};
      }
    },
    // 跳转汽车车型
    toTypes() {
      if ("id" in this.brand) {
        if ("id" in this.serie) {
          this.typeListShow = true;
        } else {
          this.$.toast("请先选择车系");
        }
      } else {
        this.$.toast("请先选择品牌");
      }
    },
    // 获取汽车车型
    getType(params) {
      this._type = this.type;
      this.type = params.item;
      this.typeListShow = false;
      // 跳转
      if (this.$route.params.is != "select") {
        this.toPreAppointment(this.type, "product");
      } else {
        this.toCompare(this.type);
      }
    },
    // 跳转到我的车辆
    toSignedCar() {
      if (this.signedCars.length > 0) {
        this.signedCarsShow = true;
      }
    },
    // 获取我的车辆信息
    getSignedCar(params) {
      this.showCar = {};
      showCarFormat(this.showCar, params.item);
      this.signedCarsShow = false;

      // 跳转
      this.toPreAppointment(this.showCar, "car");
    },
    // 跳转到确认信息页面
    toPreAppointment(car, ID_Type) {
      alert("route start");
      this.$router.push({
        name: "preAppointment",
        params: {
          is: this.$route.params.is
        },
        query: {
          car: JSON.stringify(car)
          // brand: JSON.stringify(this.brand),
          // serie: JSON.stringify(this.serie)
        }
      });
    },
    // 跳转到车辆对比页面
    toCompare(car) {
      // getRouteStatusPush 路由状态,该参数用来解决页面流转问题 是否是[car_compare] push到 [selectCar] 的
      console.log(carStore)
      if (this.fromRoute == 'car_compare' && !carStore.getters.getRouteStatusPush) {
        carStore.commit("setId", '')
        carStore.commit("setIds", [])
      }

      let ids = carStore.getters.getIds;
      if (ids.indexOf(car.id) == -1) {
        ids.push(car.id);
      } else {
        ids = [car.id];
      }
      if (this.fromRoute == 'car_compare' && carStore.getters.getRouteStatusPush) {
        // getRouteStatusPush 路由状态,该参数用来解决页面流转问题 是否是[car_compare] push到 [selectCar] 的
        // 还原状态 routeStatusPush = false
        carStore.commit("setRouteStatusPush", false)
        this.$router.back()
      } else {
        this.$router.push({
          name: "car_compare",
          params: {
            id: carStore.getters.getId
          }
        });
      }
    },
    brandListClose() {
      this.brandListShow = false;
    },
    serieListClose() {
      this.serieListShow = false;
    },
    typeListClose() {
      this.typeListShow = false;
    }
  },
  activated() {
    if (this.$route.params.is == "select") {
      this.brand = {}
      this.serie = {}
      this.type = {}
      // 如果不是从车型比较页面进入的车型选择, 清空store
      // vm.fromRoute = from.name
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 获取注册的车辆信息
      QueryCarInfoList.bind(vm)(
        {
          userId: vm.user.userId,
          plateNumber: "",
          vin: "",
          type: "",
          carId: vm.user.carId
        },
        resp => {
          vm.signedCars = resp.ownCars;
          vm.showCar = {};
          vm.signedCars.forEach(function (carInfo) {
            // 默认绑定的第一辆车为准
            if (carInfo.defaultCar == "1") {
              showCarFormat(vm.showCar, carInfo);
              vm.user.carId = carInfo.id;
              // 如果是第一次进入, 默认以绑定的车辆为选择车辆并预约
              if (
                vm.firstVisit &&
                to.params.is != "try" &&
                to.params.is != "select"
              ) {
                vm.firstVisit = false;
                vm.getSignedCar({ item: carInfo });
              }

              if (to.params.is == "select") {
                vm.brand = {}
                vm.serie = {}
                vm.type = {}
                // 如果不是从车型比较页面进入的车型选择, 清空store
                vm.fromRoute = from.name
              }
            }
          });
        }
      );
    });
  }
};
// showCar 数据字段格式化
function showCarFormat(showCar, info) {
  showCar.image = info.brandLogo;
  showCar.name = info.series;
  showCar.plateNumber = info.plateNumber;
  // showCar.id = info.id;
}
</script>

<style lang="scss" scoped>
.smaller-header {
  font-size: 12px;
  color: #929292;
  padding: 12px;
  background: #efefef;
}

.item {
  border-bottom: 1px solid #cbcbcb;
  display: flex;
  align-items: center;
  &.brand {
    padding: 5px;
    img {
      width: 40px;
      height: 40px;
    }
    span {
      margin-left: 10px;
    }
  }
  &.serie {
    padding: 5px;
    img {
      width: 70px;
      height: 50px;
    }
    span {
      margin-left: 10px;
    }
  }
  &.product {
    padding: 25px;
    img {
      width: 70px;
      height: 50px;
    }
    span {
      margin-left: 10px;
    }
  }
}
.grid-cancel button {
  background: #fa992e;
  border: 0;
  outline: none;
  padding: 10px 50px;
  color: #fff;
  font-size: 13px;
  border-radius: 3px;
}
</style>


